<?php
namespace App\Services;
use App\Models\Cart;
use App\Models\MallFullReduction;

class FullReductionService {

    /**
     * 获取满减包邮剩余多少
     * @param $producer_id
     * @param $user
     * @return int|string
     */
    public static function handle($producer_id, $user) {
        $reduction_paid_amount = 0;

        $list = Cart::withCertain('product', ['producer_id','specs_detail_info', 'amount', 'vip_amount', 'is_specs', 'stock', 'is_full_reduction'])
            ->where('producer_id', $producer_id)->where('user_id', $user->id)->where('is_direct', 0)->get()->toArray();

        $total_amount = MallFullReduction::where('merchant_id', $producer_id)->value('amount') ?? 0;

        if (empty($list))
            return $total_amount;

        foreach ($list as $val) {
            $product = $val['product'];
            if (!$product['is_full_reduction'])
                continue;

            if ($product['is_specs']) {
                $match_val = $product['specs_detail_info'][$val['specs_str']] ?? [];
                $amount = $match_val['amount'] ?? '';
                if (!$amount)
                    continue;
                $vip_amount = $match_val['vip_amount'] ?? '';
                $amount_yuan = !$user->is_vip ? $amount : $vip_amount;
            } else {
                $amount_yuan = format_yuan(!$user->is_vip ? $product['amount'] : $product['vip_amount']);
            }
            $reduction_paid_amount += $amount_yuan * $val['buy_num'] * 100;
        }

        //获取满减包邮
        $amount = $total_amount * 100;
        $left_amount = ($amount - $reduction_paid_amount) >0 ? format_yuan($amount - $reduction_paid_amount ) : 0;

        return $left_amount;
    }
}
